package gw.com.android.app;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.os.Environment;
import android.text.TextUtils;

import com.gwtsz.gts2.hx.R;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.utils.ChannelUtil;
import www.com.library.app.Logger;
import www.com.library.util.DeviceUtil;
import www.com.library.util.Md5;
import www.com.library.util.StringUtils;

/**
 * 项目配置管理类
 *
 * @author Administrator
 */
public class GTConfig {

    public String alias = Md5.md5(DeviceUtil.instance().getMacAddr(AppMain.getApp()).getBytes());

    /* Definitions of debug flags */
    public static final int MAX_LOGIN_LIST_SIZE = 10;
    public static final String LANG_ZH_TW = "zh_TW";
    public static final String LANG_ZH_CN = "zh_CN";
    public static String DEFAULT_LANGUAGE = LANG_ZH_CN;// 默认简体

    public static final String COLOR_GREEN_RISE = "greenRed";
    public static final String COLOR_RED_RISE = "redGreen";

    /**
     * 应用中新功能标识常量
     */
    public static final int ACC_TYPE_GUEST = 0; // 游客登录
    public static final int ACC_TYPE_REAL = 1; // 真实账户登录
    public static final int ACC_TYPE_DEMO = 2; // 模拟账户登录
    public static final int ACC_TYPE_PHONE = 3; // 手机号登录
    public static final int ACC_TYPE_ACTIVE = 4; // 真实激活用户
    public static final int ACC_TYPE_NOTACTIVE = 5; // 真实未激活用户

    public final static String FROM_QUOTE = "from_quote";
    public final static String FROM_NEEDLOGIN = "from_need_login";

    public static final String INTENT_QQ = "mqqwpa://im/chat?chat_type=wpa&uin=00000000&version=1";// 跳转到QQ

    private static final String PREFERENCE_NAME = "GTS2"; // 产品名称
    private static final String PREF_LANGUAGE = "Language";// 语言key
    private static final String PREF_LOGIN_NAME_LIST = "NameList"; // 账号登陆名集合
    private static final String PREF_LAST_LOGIN_NAME = "LoginName"; // 上次用户登录账号
    private static final String PREF_PHONE_REAL_ACCOUNT = "PhoneRealAccount"; // 上次用户登录手机号绑定的真实账号
    private static final String PREF_PHONE_DEMO_ACCOUNT = "PhoneDemoAccount"; // 上次用户登录手机号绑定的模拟账号
    private static final String PREF_REMEMBER_PASSWORD = "RememberPw"; // 是否记住密码key
    private static final String PREF_LAST_LOGIN_TYPE = "AccType";//上次登录类型，真实或模拟
    private static final String PREF_COLOR_CONFIG = "ColorConfig"; //红涨绿跌，绿涨红跌保存对象
    public static final String PREF_KEEP_SCREEN = "keepscreenonopen"; //屏幕常亮开关保存对象
    public static final String PREF_ORDER_NOTICE_SOUND = "pendingOrderNoticeSoundOnisopen"; //订单成交声音开关保存对象
    public static final String PREF_ORDER_NOTICE_SHAKE = "pendingOrderNoticeVibratorOnisopen"; //订单成交震动开关保存对象
    public static final String PREF_USER_HELP = "userfirst";//用戶是否已经使用新手帮助界面
    public static final String PREF_USER_QQ_SERVICE = "qqServiceFirs";//用戶是否已经打开qq客服功能
    public static final String PREF_AUTO_LOGIN = "openAutoLoginisopen2";//自动登录设置保存
    public static final String PRE_OPEN_GESTURE = "openGestureIdPwd";//是否开启手势密码验证
    public static final String PREF_ASSET_SHOW = "KeepAssetsshow";//资金隐藏保存，默认显示
    public static final String PREF_TIPS_PRECENT = "isRangeclick";//行情涨跌幅点击设置保存
    public static final String PREF_NEW_PRICE = "keepcurrentklineshow";//是否绘制现价线,默认false
    public static final String PREF_HOLLOW_LINE = "keephollowklineshow";//是否需要空心阳线,默认false
    public static final String PREF_RISE_QUOTE = "riseQuote";//是否显示涨跌模式行情,默认false
    public static final String PREF_BIG_QUOTE = "priceFontBig";//是否放大行情报价,默认false
    public static final String PREF_HOT_QUOTE = "hotQuote";//是否点击了热门产品按钮,默认false
    //	public static final String CHANNEL_KEY = "channel"; //渠道key
    public static final String PREF_SHARETIPS_SHOW = "isShareTipsShow"; //平仓分享弹窗当日是否显示过
    public static final String PREF_ISSHARED = "isShared"; //当日是否分享过
    public static final String PREF_CONFIG_VERSION = "ConfigVersion"; //配置文件本地保存的版本号
    private static final String PREF_QUOTE_GUIDE = "QuoteLayerGuide"; //行情引导页
    private static final String PREF_DEPOSIT_GUIDE = "DepositGuide"; //充值引导页

    public static final String PREF_ORDER_TRADE = "pendingOrderNoticeTrade"; //推送设置-交易时机提醒
    public static final String PREF_ORDER_QUOTE = "pendingOrderNoticeQuote"; //推送设置-行情推送
    public static final String PREF_ORDER_ONLIVE = "pendingOrderNoticeOnlive"; //推送设置-直播开课
    public static final String PREF_ORDER_NEWS = "pendingOrderNoticeNews"; //推送设置-资讯
    public static final String PREF_HOME_VIDEOS = "PREF_HOME_VIDEOS";//首页下载保持视频的TAG
    public static final String PREF_SYS_COMPLETE_BANK = "PREF_SYS_COMPLETE_BANK";//完善资料tg
    public static final String PREF_LOCAL_FIRST_LOGIN = "_localFirstLogin"; //账号在本地是否第一次登陆
    public static final String PREF_REAL_ACCOUNT_LOGINED = "realAccountLogined"; //是否有真实账号登陆过
    public static final String PREF_TOP_NEWS_MARK = "topNewsMark"; //点击过的要闻id

    public static final String PREF_NEW_NOTICE_RED_POINT = "newNoticeRedPoint"; //新用户须知红点

    /**
     * sd卡路径
     */
    private String mRootDirectory = "";
    /**
     * 用户类型
     */
    private int mAccountType = ACC_TYPE_REAL;
    /**
     * 是否從登錄頁登录
     */
    public boolean isFromLogin = false;
    /**
     * 是否为手机号登录
     */
    public boolean isPhoneLogin = false;
    /**
     * 用户登录的账号关联的手机号
     **/
    public String mCurLoginPhone = "";
    /**
     * 当前登录用户账号
     */
    public String mCurName = "";
    /**
     * 系统参数保存对象
     */
    private SharedPreferences mSysPreferences;
    /**
     * 用户参数保存对象
     */
    private SharedPreferences mUsrPreferences;

    /**
     * 用户的临时密码保存
     **/
    public String mUserPwd = "";
    /**
     * 上次登录的类型
     */
    public int mLastAccountType = ACC_TYPE_GUEST;
    /**
     * 标识是否被登出，true标识被登出，false标识没有
     */
    public boolean mHasKickOut = false;
    /**
     * 用户是否从通知栏进入应用
     */
    public boolean hasNotify = false;
    /**
     * 产品按什么排序方式
     */
    public int mSortType = AppContances.SORT_NORMAL_TYPE;
    /**
     * 标识是否已经显示主面板，做重连加载圈逻辑处理，进入过MainTab就标识设置为true
     */
    public boolean hasShowMain = false;
    /**
     * 是否有版本更新
     */
    public boolean hasNewVersion = false;
    /**
     * 是否加载成功过广告弹层
     */
    public boolean loadedAdsPop = false;
    /**
     * 是否嵌套首页已经发送行情订阅
     */
    public boolean isSubscribed = false;
    /**
     * 登陆成功后，客户端生成的唯一ID
     */
    public String mSession = "";
    /**
     * openapi 登陆成功后请求token 用于活动链接
     */
    public String mOpenApiToken = "";
    /**
     * 保存账号的A或N的信息  active or notActive
     */
    private Map<String, Integer> activeMap;
    /**
     * 当前类对象
     */
    private static GTConfig mOwnConfig = new GTConfig();

    public static GTConfig instance() {
        if (null == mOwnConfig) {
            mOwnConfig = new GTConfig();
        }
        if (null == mOwnConfig.mSysPreferences) {
            mOwnConfig.readPreference(AppMain.getApp());
        }
        return mOwnConfig;
    }

    public String getRootDirectory() {
        if (TextUtils.isEmpty(mRootDirectory)) {
            final String externalStorageState = Environment.getExternalStorageState();
            if (Environment.MEDIA_MOUNTED.equals(externalStorageState)) {
                mRootDirectory = Environment.getExternalStorageDirectory() + "/" + AppMain.getAppString(R.string.filename);
            } else {
                mRootDirectory = AppMain.getApp().getCacheDir().getAbsolutePath();
            }
            Logger.i("mRootDirectory = " + mRootDirectory);
        }
        File file = new File(mRootDirectory);
        if (!file.exists()) {
            file.mkdirs();
        }
        return mRootDirectory;
    }

    public GTConfig() {
        mSysPreferences = null;
        mUsrPreferences = null;
        mAccountType = ACC_TYPE_REAL;
    }

    /**
     * 返回登陆账号列表
     *
     * @return
     */
    public ArrayList<String> getLoginList() {
        String list = null;
        String[] mLoginnameList;

        list = mSysPreferences.getString(PREF_LOGIN_NAME_LIST, null);
        if (null == list || "".equals(list)) {
            mLoginnameList = null;
        } else {
            mLoginnameList = list.split(",");
        }
        return StringUtils.removeNullStrInStrArr(mLoginnameList);
    }

    /**
     * 将原来分账号类型保存的账号统一保存
     *
     * @return
     */
    public void setLoginList() {
        StringBuilder listBuilder = new StringBuilder();
        String list = null;
        String list1 = null;
        String list2 = null;
        String list3 = null;

        list1 = mSysPreferences.getString(PREF_LOGIN_NAME_LIST + "real", null);
        list2 = mSysPreferences.getString(PREF_LOGIN_NAME_LIST + "demo", null);
        if (null != list2 && !"".equals(list2)) {
            listBuilder.append(list2).append(",");
        }
        if (null != list1 && !"".equals(list)) {
            listBuilder.append(list1);
        }
        list3 = mSysPreferences.getString(PREF_LOGIN_NAME_LIST, null);
        if (null != list3 && !"".equals(list3)) {
            listBuilder.append(list3);
        }
        list = listBuilder.toString();
        if (null == list || "".equals(list)) {
            return;
        }
        Editor editor = mSysPreferences.edit();
        editor.putString(PREF_LOGIN_NAME_LIST + "real", "");
        editor.putString(PREF_LOGIN_NAME_LIST + "demo", "");
        editor.putString(PREF_LOGIN_NAME_LIST, list);
        editor.apply();
    }


    /**
     * 返回登陆账号列表
     *
     * @return
     */
    public ArrayList<String> getLoginList(int accountType) {
        String list = null;
        if (accountType == ACC_TYPE_REAL) {
            list = mSysPreferences.getString(PREF_LOGIN_NAME_LIST + "real", null);
        } else {
            list = mSysPreferences.getString(PREF_LOGIN_NAME_LIST + "demo", null);
        }
        String[] mLoginList = null;
        if (null == list || "".equals(list)) {
            mLoginList = null;
        } else {
            mLoginList = list.split(",");
        }
        return StringUtils.removeNullStrInStrArr(mLoginList);
    }

    /**
     * 更新登录账号列表
     */
    public void updateLoginList(String username, List<String> loginList) {
        if (null != loginList) {
            if (username.equals(getLoginName())) {
                saveLoginName("", "");
            }
            String newLoginListStr = "";
            for (int i = 0; i < loginList.size(); i++) {
                String str = loginList.get(i).toString();
                if (null == str || "".equals(str)) {
                    return;
                }
                if (0 == i) {
                    newLoginListStr = str;
                } else {
                    newLoginListStr = newLoginListStr + "," + str;
                }
            }
            Editor editor = mSysPreferences.edit();
            editor.putString(PREF_LOGIN_NAME_LIST, newLoginListStr);
            editor.putString(username, "");
            editor.apply();
        }
    }

    /**
     * 新的用户名保存到用户列表
     *
     * @param newLoginname
     * @return
     */
    private String loginanmeArrayToConcateString(String newLoginname) {
        ArrayList<String> mLoginnameList = getLoginList();
        if (mLoginnameList == null)
            return newLoginname;

        int ignoreCnt = mLoginnameList.size() + 1 - MAX_LOGIN_LIST_SIZE;
        int count = 0;
        boolean findLoginname = false;
        String list = "";
        for (String name : mLoginnameList) {
            if (count < ignoreCnt) {
                if (name.equals(newLoginname)) {
                    list += name + ",";
                    ignoreCnt++;
                } else {
                    clearUserSharedPreferences(name);
                }
            } else {
                if (name.equals(newLoginname))
                    findLoginname = true;
                list += name + ",";
            }

            count++;
        }

        if (!findLoginname)
            list += newLoginname;

        return list;
    }

    /**
     * 保存用户登陆信息
     *
     * @param loginname
     * @param pass
     */
    public void saveLoginInfo(String loginname, String pass) {
        if (loginname == null || loginname.isEmpty())
            return;
        saveLoginName(loginname, pass);
        String list = loginanmeArrayToConcateString(loginname);
        Editor editor = mSysPreferences.edit();
        Logger.e("accounttype = " + getAccountType() + ", " + list);
        editor.putString(PREF_LOGIN_NAME_LIST, list);
        editor.apply();
        getLoginList();
    }

    /**
     * 获取用户手机登陆的账户信息
     *
     * @param loginPhoneNo
     * @paramaccountType
     */
    public String getPhoneLoginInfo(String loginPhoneNo, int accountType) {
        if (accountType == ACC_TYPE_REAL) {
            return mSysPreferences.getString(loginPhoneNo + PREF_PHONE_REAL_ACCOUNT, "");
        } else {
            return mSysPreferences.getString(loginPhoneNo + PREF_PHONE_DEMO_ACCOUNT, "");
        }

    }

    /**
     * 保存用户手机登陆的账户信息
     *
     * @param loginname
     */
    public void savePhoneLoginInfo(String loginPhoneNo, String loginname) {
        Editor editor = mSysPreferences.edit();
        if (getAccountType() == ACC_TYPE_REAL) {
            editor.putString(loginPhoneNo + PREF_PHONE_REAL_ACCOUNT, loginname);
        } else {
            editor.putString(loginPhoneNo + PREF_PHONE_DEMO_ACCOUNT, loginname);
        }
        editor.apply();

    }

    /**
     * 上次登录的用户名
     */
    public String getLoginName() {
        String loginName = mSysPreferences.getString(PREF_LAST_LOGIN_NAME, "");
        if ("".equals(loginName)) {
            if (getAccountType() == ACC_TYPE_REAL) {
                return mSysPreferences.getString(PREF_LAST_LOGIN_NAME + "real", "");
            } else {
                return mSysPreferences.getString(PREF_LAST_LOGIN_NAME + "demo", "");
            }
        }
        return loginName;
    }

    /**
     * 保存上次的登陆用户名
     */
    public void saveLoginName(String loginName, String pass) {
        Editor editor = mSysPreferences.edit();
        editor.putString(PREF_LAST_LOGIN_NAME, loginName);
        if (isRememberPassword()) {
            editor.putString(loginName, pass);
        } else {
            editor.putString(loginName, "");
        }
        editor.apply();
        saveLoginType(loginName);
    }

    /**
     * 綁定完賬戶后要更新保存的賬戶信息，如密碼
     */
    public void updateLoginInfo(String loginName, String passWord, int accountType) {
        ArrayList<String> mLoginnameList = getLoginList();
        if (null != mLoginnameList) {
            for (int i = 0; i < mLoginnameList.size(); i++) {
                String str = mLoginnameList.get(i).toString();
                if (null == str || "".equals(str)) {
                    return;
                }
                if (isPhoneLogin) {
                    if (!"".equals(mCurLoginPhone) && str.equals(mCurLoginPhone)) {
                        saveLoginName(mCurLoginPhone, passWord);
                        break;
                    }
                } else {
                    if (str.equals(loginName)) {
                        saveLoginName(loginName, passWord);
                        break;
                    }
                }
            }
        }
    }

    /**
     * 根据用户名获取登陆密码
     */
    public String getLoginPass(int type, String loginname) {
        String loginPass = mSysPreferences.getString(loginname, "");
        if ("".equals(loginPass)) {
            loginPass = mSysPreferences.getString(loginname + "real", "");
        }
        if ("".equals(loginPass)) {
            loginPass = mSysPreferences.getString(loginname + "demo", "");
        }
        return loginPass;
    }

    /**
     * 根据用户名获取登陆密码
     */
    public String getLoginPass(String loginname) {
        String loginPass = mSysPreferences.getString(loginname, "");
        if ("".equals(loginPass)) {
            loginPass = mSysPreferences.getString(loginname + "real", "");
        }
        if ("".equals(loginPass)) {
            loginPass = mSysPreferences.getString(loginname + "demo", "");
        }
        return loginPass;
    }

    /**
     * 是否记住密码
     */
    public boolean isRememberPassword() {
        return mSysPreferences.getBoolean(PREF_REMEMBER_PASSWORD, true);
    }

    /**
     * 设置保存登陆密码的标识
     */
    public void savePasswordFlag(boolean isRemember) {
        Editor editor = mSysPreferences.edit();
        editor.putBoolean(PREF_REMEMBER_PASSWORD, isRemember);
        editor.apply();
    }

    /**
     * 清除密码
     */
    public void clearPassword(String loginname) {
        ArrayList<String> list = getLoginList();

        if (list == null || list.size() < 1) {
            return;
        }
        for (int i = 0; i < list.size(); i++) {
            if (loginname.equals(list.get(i))) {
                continue;
            }
            Editor editor = mSysPreferences.edit();
            editor.putString(list.get(i), "");
            editor.apply();
        }
    }

    public void addAccountActiveState(String account, boolean isActive) {
        if (activeMap == null) {
            activeMap = new HashMap<>();
        }
        activeMap.put(account, isActive ? 1 : -1);
    }

    /**
     * @return 1: Active  -1:notActive  0:unknow
     */
    public int isAccountActive() {
        return isAccountActive(mCurName);
    }


    /**
     * @return 1: Active  -1:notActive  0:unknow
     */
    private int isAccountActive(String account) {
        if (activeMap != null && activeMap.containsKey(account)) {
            return activeMap.get(account);
        }
        return 0;
    }

    /**
     * 保存账号类型
     */
    public void saveLoginType(String loginName) {
        Editor editor = mSysPreferences.edit();
        if (isPhoneLogin) {
            editor.putInt(loginName + PREF_LAST_LOGIN_TYPE, mAccountType);
        } else {
            editor.putInt(PREF_LAST_LOGIN_TYPE, mAccountType);
        }
        editor.apply();
    }

    // 登陆统计信息上传失败保存在本地
    public void savaloginUploadErrinfo(String loginInfo) {

        Editor editor = mSysPreferences.edit();
        editor.putString("LoginInfo", loginInfo);
        editor.apply();

    }

    // 登陆统计信息上传成功，清除本地信息
    public void removeloginInfo() {
        Editor editor = mSysPreferences.edit();
        // editor.putString("LoginInfo", loginInfo);
        editor.remove("LoginInfo");
        editor.apply();
    }

    /**
     * 获取下单时显示的手数 1) 如果是第一次下单,默认取手数列表的第一项 2) 如果不是第一次下单,则取上次下单的手数
     *
     * @param mPrdCode   当前产品code
     * @param defaultLot 默认手数
     */
    public String getProductOrderLot(int mPrdCode, String defaultLot) {
        if (null != mUsrPreferences) {
            String str = mUsrPreferences.getString(mPrdCode + "CurLot", defaultLot);
            if (str.length() < 1) {
                return defaultLot;
            }
            return str;
        } else {
            return defaultLot;
        }
    }

    /**
     * 下单提交成功后保存手数
     *
     * @param mPrdCode        当前产品code
     * @param curSubmittedLot 提交的手数
     */
    public void saveProductOrderLot(int mPrdCode, String curSubmittedLot) {
        if (null != mUsrPreferences) {
            Editor editor = mUsrPreferences.edit();
            editor.putString(mPrdCode + "CurLot",
                    String.valueOf(curSubmittedLot));
            editor.apply();
        }
    }

    /**
     * 设置最大偏移量 1) 如果是第一次下单,取默认最大偏移量 2) 如果不是第一次下单,则取上次输入的最大偏移量
     *
     * @param mPrdCode     当前产品code
     * @param defaultRange 默认最大偏移量
     */
    public String getProductRange(int mPrdCode, String defaultRange) {
        if (null != mUsrPreferences) {
            String range = mUsrPreferences.getString(mPrdCode + "CurRangePoint", defaultRange);
            if (range.length() < 1) {
                return defaultRange;
            }
            return range;
        } else {
            return defaultRange;
        }
    }

    /**
     * 下单提交成功后保存最大偏移量
     *
     * @param mPrdCode          当前产品code
     * @param curSubmittedRange 提交的最大偏移量
     */
    public void saveProductOrderRange(int mPrdCode, String curSubmittedRange) {
        if (null != mUsrPreferences) {
            Editor editor = mUsrPreferences.edit();
            editor.putString(mPrdCode + "CurRangePoint", curSubmittedRange);
            editor.apply();
        }
    }

    /**
     * 返回账号类型
     *
     * @return
     */
    public int getAccountType() {
        return mAccountType;
    }

    public void setAccountType(int accType) {
        mAccountType = accType;
    }

    /**
     * 获取上次登录的类型
     *
     * @return
     */
    public int getLastAccountType() {
        return mSysPreferences.getInt(PREF_LAST_LOGIN_TYPE, ACC_TYPE_REAL);
    }

    /**
     * 获取上次手机号登录的类型
     *
     * @return
     */
    public int getLastPhoneLoginType(String loginPhoneNo) {
        return mSysPreferences.getInt(loginPhoneNo + PREF_LAST_LOGIN_TYPE, ACC_TYPE_REAL);
    }

    public SharedPreferences readPreference(Context ctx) {
        mSysPreferences = ctx.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);

        /* Load login information */
        setLoginList();
        getLoginList();
        /* Language */
        // 初始化语言类型,判断当前系统语言是否为繁体,不是繁体的默认为中文简体
        if (ctx.getResources().getConfiguration().locale.getLanguage().equals("tw")) {
            DEFAULT_LANGUAGE = LANG_ZH_TW;
        } else {
            DEFAULT_LANGUAGE = LANG_ZH_CN;
        }
        /* Account Type */
        setAccountType(mSysPreferences.getInt(PREF_LAST_LOGIN_TYPE, ACC_TYPE_REAL));

        return mSysPreferences;
    }

    /* Create a shared preferences for isNext user */
    public SharedPreferences readUserPreference() {
        if (mCurName == null || mCurName.isEmpty())
            mUsrPreferences = AppMain.getApp().getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        else {
            mUsrPreferences = AppMain.getApp().getSharedPreferences(PREFERENCE_NAME + mCurName, Context.MODE_PRIVATE);
        }

        return mUsrPreferences;
    }

    public String getLanguage() {
        if (null != mSysPreferences) {
            return mSysPreferences.getString(PREF_LANGUAGE, DEFAULT_LANGUAGE);
        }
        return DEFAULT_LANGUAGE;
    }

    /**
     * 保存选择的语言
     */
    public void saveLanguage(String languageValue) {
        String language = (languageValue == null || languageValue.isEmpty()) ? DEFAULT_LANGUAGE : languageValue;
        Editor editor = mSysPreferences.edit();
        editor.putString(PREF_LANGUAGE, language);
        editor.apply();
    }

    /**
     * 配置语言
     */
    public void configureLanguage(Context baseCtx) {
        /* Set Language */
        final String language = getLanguage();
        Logger.e("configureLanguage languge :: " + language);
        if (language != null && !language.isEmpty()) {
            Locale locale;
            String[] langParts = language.split("_");
            if (langParts.length >= 2)
                locale = new Locale(langParts[0], langParts[1]);
            else
                locale = new Locale(langParts[0]);

            Locale.setDefault(locale);
            Configuration config = new Configuration();
            config.locale = locale;
            baseCtx.getResources().updateConfiguration(config, null);
        }
    }

    /**
     * 保存颜色设置
     */
    public void savePrefColorConfig(String mColor) {
        String color = (mColor == null || mColor.isEmpty()) ? COLOR_GREEN_RISE : mColor;
        Editor editor = mSysPreferences.edit();
        editor.putString(PREF_COLOR_CONFIG, color);
        editor.apply();
    }

    /**
     * 获取颜色设置
     */
    public String getPrefColorConfig() {
        if (null != mSysPreferences) {
            return mSysPreferences.getString(PREF_COLOR_CONFIG, COLOR_GREEN_RISE);
        }
        return COLOR_GREEN_RISE;
    }

    /**
     * 保存配置文件版本号设置
     */
    public void saveConfigVersion(String version) {
        String version1 = (version == null || version.isEmpty()) ? "" : version;
        Editor editor = mSysPreferences.edit();
        editor.putString(PREF_CONFIG_VERSION, version1);
        editor.apply();
    }

    /**
     * 获取配置文件版本号设置
     */
    public String getConfigVersion() {
        if (null != mSysPreferences) {
            return mSysPreferences.getString(PREF_CONFIG_VERSION, "");
        }
        return COLOR_GREEN_RISE;
    }

    /**
     * 设置行情引导页已显示
     */
    public void setQuoteLayerShowed(boolean showed) {
        if (null != mSysPreferences) {
            mSysPreferences.edit().putBoolean(PREF_QUOTE_GUIDE, showed).apply();
        }
    }

    /**
     * 获取行情引导页的显示状态
     */
    public boolean isQuoteLayerShowed() {
        return mSysPreferences != null && mSysPreferences.getBoolean(PREF_QUOTE_GUIDE, false);
    }

    /**
     * 设置充值引导已显示
     */
    public void setNewNoticeClicked(boolean clicked) {
        if (null != mSysPreferences) {
            mSysPreferences.edit().putBoolean(getNewNoticeClickKey(), clicked).apply();
        }
    }

    /**
     * 获取充值引导页的显示状态
     */
    public boolean isNewNoticeClicked() {
        return mSysPreferences != null && mSysPreferences.getBoolean(getNewNoticeClickKey(), false);
    }

    private String getNewNoticeClickKey() {
        return PREF_NEW_NOTICE_RED_POINT + mCurName;
    }

    /**
     * 图标是否为黑夜模式
     */
    public void setChartIsNight(boolean isNight) {
        if (mSysPreferences != null) {
            mSysPreferences.edit().putBoolean(getChartNightModeKey(), isNight).apply();
        }
    }

    /**
     * 图标是否为黑夜模式
     */
    public boolean isChartNight() {
        return mSysPreferences != null && mSysPreferences.getBoolean(getChartNightModeKey(), false);
    }

    private String getChartNightModeKey() {
        return mCurName + "_chart_is_night";
    }

    /**
     * 行情板块是否为黑夜模式
     */
    public void setQuoteChartIsNight(boolean isNight) {
        if (mSysPreferences != null) {
            mSysPreferences.edit().putBoolean(getQuoteChartNightModeKey(), isNight).apply();
        }
    }

    /**
     * 行情板块是否为黑夜模式
     */
    public boolean isQuoteChartNight() {
        return mSysPreferences != null && mSysPreferences.getBoolean(getQuoteChartNightModeKey(), false);
    }

    private String getQuoteChartNightModeKey() {
        return mCurName + "_quote_chart_is_night";
    }

    /**
     * 项目中所有开关及其他功能返回值
     */
    public boolean getBooleanValue(String type) {
        return mSysPreferences.getBoolean(type, false);
    }

    /**
     * 项目中所有开关及其他功能返回值
     */
    public boolean getBooleanValue(String type, boolean defaultValue) {
        return mSysPreferences.getBoolean(type, defaultValue);
    }

    public long getLongValue(String key, long defaultValue) {
        return mSysPreferences.getLong(key, defaultValue);
    }

    public void setLongValue(String key, long value) {
        mSysPreferences.edit().putLong(key, value).apply();
    }

    public String getStringValue(String key) {
        return mSysPreferences.getString(key, null);
    }

    public void setStringValue(String key, String value) {
        mSysPreferences.edit().putString(key, value).apply();
    }

    /**
     * 项目中保存今天是否操作过的值
     *
     * @param type 保存数据的tag值
     */
    public void setStringIsToday(String type, String time) {
        Editor editor = mSysPreferences.edit();
        editor.putString(type, time);
        editor.apply();
    }

    /**
     * 项目中判断是否是今天操作过的返回值
     */
    public String getStringIsToday(String type) {
        return mSysPreferences.getString(type, "");
    }

    /**
     * 项目中所有开关及其他功能保存方法
     *
     * @param type 保存数据的tag值
     */
    public void setBooleanValue(String type, boolean isBoolean) {
        Editor editor = mSysPreferences.edit();
        editor.putBoolean(type, isBoolean);
        editor.apply();
    }

    public void addTopNewsMark(String id) {
        List<String> mark = getTopNewsMark();
        if (mark == null) {
            mSysPreferences.edit().putString(PREF_TOP_NEWS_MARK, id).apply();
            return;
        }
        if (mark.size() >= 40) {
            mark.remove(0);
        }
        mark.add(id);
        StringBuilder sb = new StringBuilder();
        int size = mark.size();
        for (int i = 0; i < size; i++) {
            if (i == size - 1) {
                sb.append(mark.get(i));
            } else {
                sb.append(mark.get(i)).append(",");
            }
        }
        mSysPreferences.edit().putString(PREF_TOP_NEWS_MARK, sb.toString()).apply();
    }

    public List<String> getTopNewsMark() {
        String value = mSysPreferences.getString(PREF_TOP_NEWS_MARK, null);
        if (!TextUtils.isEmpty(value)) {
            String[] split = value.split(",");
            List<String> list = new ArrayList<>();
            Collections.addAll(list, split);
            return list;
        }
        return null;
    }

    public boolean getPushState(String key) {
        key = GTConfig.instance().mCurName + "_push_" + key;
        return GTConfig.instance().getBooleanValue(key, true);
    }

    public void setPushState(String key, boolean state) {
        key = GTConfig.instance().mCurName + "_push_" + key;
        GTConfig.instance().setBooleanValue(key, state);
    }

    /**
     * 清除用户缓存对象
     */
    private void clearUserSharedPreferences(String username) {
        SharedPreferences pref = AppMain.getApp().getSharedPreferences(PREFERENCE_NAME + username, Context.MODE_PRIVATE);
        Editor editor = pref.edit();
        editor.clear();
        editor.apply();
    }

    /**
     * 设置推送的标签
     */
    public void setJpushAliasAndTags(TagAliasCallback mAliasCallback, String alias) {
        if (StringUtils.isEmpty(alias)) {
            alias = getDefaultJpushAlias();
        }
        JPushInterface.setAliasAndTags(AppMain.getApp(), alias, getJpushTagSet(), mAliasCallback);
    }

    public String getDefaultJpushAlias() {
        String alias = GTConfig.instance().getLoginName();
        if (DeviceUtil.instance().isPhone(alias)) {
            if (GTConfig.instance().getLastPhoneLoginType(alias) == GTConfig.ACC_TYPE_DEMO) {
                alias = GTConfig.instance().getPhoneLoginInfo(alias, GTConfig.ACC_TYPE_DEMO);
            } else {
                alias = GTConfig.instance().getPhoneLoginInfo(alias, GTConfig.ACC_TYPE_REAL);
            }
        }
        if (StringUtils.isEmpty(alias)) {
            alias = Md5.md5(DeviceUtil.instance().getMacAddr(AppMain.getApp()).getBytes());
        }
        return alias;
    }


    /**
     * 返回推送标签的相关值
     */
    public Set<String> getJpushTagSet() {
        String Language = "Lang_" + getLanguage();
        String Account = "";
        String CompanyId = "";
        Set<String> tagSet = new LinkedHashSet<String>();
        int curAccType = GTConfig.instance().getAccountType();
        CompanyId = "CompanyId_" + ConfigUtil.instance().mConfigObject.optInt(ConfigType.COMPANY_ID_TAG);
        if (curAccType == GTConfig.ACC_TYPE_REAL) {
            Account = "Account_real";
        } else if (curAccType == GTConfig.ACC_TYPE_DEMO) {
            Account = "Account_demo";
        } else {
            Account = "Account_guest";
        }

        String channelTag = new ChannelUtil().getChannelTag();
        if (!TextUtils.isEmpty(channelTag)) {
            tagSet.add(channelTag);
        }
        tagSet.add(Language);
        tagSet.add(Account);
        tagSet.add(CompanyId);
        ///////////////////////////   push  /////////////////////
        if (!getPushState("quote")) {
            tagSet.add(getPushTagName("quote"));
        }
        if (!getPushState("trade")) {
            tagSet.add(getPushTagName("trade"));
        }
        if (!getPushState("system")) {
            tagSet.add(getPushTagName("system"));
        }
        if (!getPushState("interact")) {
            tagSet.add(getPushTagName("interact"));
        }
        if (!getPushState("analyst")) {
            tagSet.add(getPushTagName("analyst"));
        }

        Logger.e("getJpushTagSet = " + tagSet.toString());
        return tagSet;
    }

    public String getPushTagName(String key) {
        return "push_" + key;
    }

    public Set<String> getUsedDiscuss(int state) {
        String key = mCurName + "_used_discuss_" + state;
        return mSysPreferences.getStringSet(key, null);
    }

    public void setUsedDiscuss(int state, Set<String> value) {
        String key = mCurName + "_used_discuss_" + state;
        mSysPreferences.edit().putStringSet(key, value).apply();
    }

}
